<template>
  <el-container>
    <el-row class="avue-view">
      <el-col :span="11">
        <basic-container>
          <avue-crud
            ref="left"
            v-model="leftForm"
            :option="leftOption"
            :table-loading="leftLoading"
            :data="leftData"
            :page="leftPage"
            :before-open="leftBeforeOpen"
            :cell-style="leftCellStyle"
            :row-style="leftRowStyle"
            @row-update="leftRowUpdate"
            @row-save="leftRowSave"
            @row-del="leftRowDel"
            @row-click="leftRowClick"
            @refresh-change="leftRefresh"
            @search-change="leftSearchChange"
            @search-reset="leftSearchReset"
            @selection-change="leftSelectionChange"
            @current-change="leftCurrentChange"
            @size-change="leftSizeChange"
            @on-load="leftOnLoad"
          >
            <template slot="menuLeft">
              <el-button
                type="danger"
                size="medium"
                icon="el-icon-delete"
                plain
                @click="leftHandleDelete"
              >
                删 除
              </el-button>
            </template>
            <template
              slot="status"
              slot-scope="{row}"
            >
              <el-tag :type="row.status? 'success':'danger'">
                {{ row.status? '启用': '禁用' }}
              </el-tag>
            </template>
          </avue-crud>
        </basic-container>
      </el-col>
      <el-col :span="13">
        <basic-container>
          <avue-crud
            ref="right"
            v-model="rightForm"
            :option="rightOption"
            :table-loading="rightLoading"
            :data="rightData"
            :page="rightPage"
            :before-open="rightBeforeOpen"
            :cell-style="rightCellStyle"
            :row-style="rightRowStyle"
            @row-update="rightRowUpdate"
            @row-save="rightRowSave"
            @row-del="rightRowDel"
            @row-click="rightRowClick"
            @refresh-change="rightRefresh"
            @search-change="rightSearchChange"
            @search-reset="rightSearchReset"
            @selection-change="rightSelectionChange"
            @current-change="rightCurrentChange"
            @size-change="rightSizeChange"
            @on-load="rightOnLoad"
          >
            <template slot="menuLeft">
              <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
                plain
                @click="rightHandleDelete"
              >
                删 除
              </el-button>
            </template>
            <template
              slot="status"
              slot-scope="{row}"
            >
              <el-tag :type="row.status? 'success':'danger'">
                {{ row.status? '启用': '禁用' }}
              </el-tag>
            </template>
          </avue-crud>
        </basic-container>
      </el-col>
    </el-row>
  </el-container>
</template>

<script>
import { mapGetters } from 'vuex'
// 字典类型
const addSysDictTypeAction = 'sys/dict/addSysDictType'
const updateSysDictTypeAction = 'sys/dict/updateSysDictType'
const removeSysDictTypeAction = 'sys/dict/removeSysDictType'
const removeSysDictTypesAction = 'sys/dict/removeSysDictTypes'
const getSysDictTypeByIdAction = 'sys/dict/getSysDictTypeById'
const getSysDictTypePageListAction = 'sys/dict/getSysDictTypePageList'

const getSysDictTypeListAction = 'sys/dict/getSysDictTypeList'
// 字典数据
const addSysDictDataAction = 'sys/dict/addSysDictData'
const updateSysDictDataAction = 'sys/dict/updateSysDictData'
const removeSysDictDataAction = 'sys/dict/removeSysDictData'
const removeSysDictDatasAction = 'sys/dict/removeSysDictDatas'
const getSysDictDataByIdAction = 'sys/dict/getSysDictDataById'
const getSysDictDataPageListAction = 'sys/dict/getSysDictDataPageList'

export default {
  name: 'Dict',
  data () {
    const statusDic = [
      {
        label: '启用',
        value: true
      },
      {
        label: '禁用',
        value: false
      }
    ]
    return {
      leftForm: {},
      leftQuery: {},
      leftLoading: true,
      leftPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      leftSelectionList: [],
      leftOption: {
        // title: '系统字典表',
        border: true,
        menu: true,
        lazy: true,
        tip: true,
        tipPlacement: 'top-start',
        index: false,
        indexLabel: '序号',
        indexFixed: true,
        selection: true,
        selectionWidth: 60,
        selectionFixed: false,
        addBtn: true,
        viewBtn: true,
        excelBtn: false,
        printBtn: false,
        dialogDrag: true,
        dialogDirection: 'rtl',
        dialogType: 'dialog',
        column: [
          {
            label: '字典名称',
            prop: 'name',
            type: 'input',
            hide: false,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入字典名称',
              trigger: 'blur'
            }]
          },
          {
            label: '状态',
            prop: 'status',
            type: 'switch',
            hide: false,
            slot: true,
            span: 24,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请选择状态',
              trigger: 'blur'
            }],
            dicData: statusDic,
            value: true
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            hide: true,
            span: 24,
            showWordLimit: true,
            maxlength: 500,
            showColumn: false,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入备注信息',
              trigger: 'blur'
            }]
          }
        ]
      },
      leftData: [],
      rightForm: {},
      rightQuery: {},
      rightLoading: false,
      rightPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      rightSelectionList: [],
      rightOption: {
        // title: '系统字典表',
        border: true,
        menu: true,
        lazy: true,
        tip: true,
        tipPlacement: 'top-start',
        index: false,
        indexLabel: '序号',
        indexFixed: true,
        selection: true,
        selectionWidth: 60,
        selectionFixed: false,
        addBtn: true,
        viewBtn: true,
        excelBtn: false,
        printBtn: false,
        dialogDrag: true,
        dialogDirection: 'rtl',
        dialogType: 'dialog',
        column: [
          {
            label: '字典类型',
            prop: 'dictTypeId',
            type: 'select',
            hide: true,
            span: 24,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请选择一个字段类型',
              trigger: 'blur'
            }],
            dicData: [],
            props: {
              label: 'name',
              value: 'id'
            }
          },
          {
            label: '键',
            prop: 'dictLabel',
            type: 'input',
            hide: false,
            span: 12,
            showWordLimit: true,
            maxlength: 100,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入字典键',
              trigger: 'blur'
            }]
          },
          {
            label: '值',
            prop: 'dictValue',
            type: 'input',
            hide: false,
            span: 12,
            showWordLimit: true,
            maxlength: 100,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入对应的字典值',
              trigger: 'blur'
            }]
          },
          {
            label: '显示顺序',
            prop: 'dictOrder',
            type: 'number',
            gutter: 24,
            hide: false,
            showColumn: false,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: false,
              message: '请输入显示顺序',
              trigger: 'blur'
            }],
            value: 1
          },
          {
            label: '状态',
            prop: 'status',
            type: 'switch',
            hide: false,
            slot: true,
            span: 24,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请选择状态',
              trigger: 'blur'
            }],
            dicData: statusDic,
            value: true
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            hide: true,
            span: 24,
            showWordLimit: true,
            maxlength: 500,
            showColumn: false,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: false,
              message: '请输入备注信息',
              trigger: 'blur'
            }]
          }
        ]
      },
      rightData: []
    }
  },
  computed: {
    ...mapGetters(['permissions', 'website']),
    leftIds () {
      const ids = []
      this.leftSelectionList.forEach((e) => {
        ids.push(e.id)
      })
      return ids
    },
    rightIds () {
      const ids = []
      this.rightSelectionList.forEach((e) => {
        ids.push(e.id)
      })
      return ids
    }
  },
  mounted () {
    this.fetchDictTypeList()
  },
  methods: {
    fetchDictTypeList () {
      this.$store.dispatch(getSysDictTypeListAction).then((res) => {
        const index = this.$refs.right.findColumnIndex('dictTypeId')
        // 设置右边的字段类型选择框数据
        this.rightOption.column[index].dicData = res.data
      }).catch((err) => {
        console.log(err)
      })
    },
    leftRowStyle ({ row, column, rowIndex }) {
      return {}
    },
    leftCellStyle ({ row, column, rowIndex, columnIndex }) {
      // return {
      //   color: 'green',
      //   fontWeight: 'bold',
      //   fontSize: '20'
      // }
      return {}
    },
    leftRowSave (row, loading, done) {
      loading()
      this.$store.dispatch(addSysDictTypeAction, row).then((res) => {
        done()
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.leftOnLoad(this.leftPage)
          this.$message({
            type: 'success',
            message: '保存操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '保存数据失败,请稍后再试!'
          })
        }
      }, (error) => {
        done()
        console.log(error)
      })
    },
    leftRowUpdate (row, index, loading, done) {
      loading()
      this.$store.dispatch(updateSysDictTypeAction, row).then((res) => {
        done()
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.leftOnLoad(this.leftPage)
          this.$message({
            type: 'success',
            message: '编辑操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '编辑数据失败,请稍后再试!'
          })
        }
      }, (error) => {
        done()
        console.log(error)
      })
    },
    leftRowDel (row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.leftLoading = true
          const idParams = { id: row.id }
          return this.$store.dispatch(removeSysDictTypeAction, idParams)
        })
        .then((res) => {
          this.leftLoading = false
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.leftOnLoad(this.leftPage)
            this.$message({
              type: 'success',
              message: '删除操作成功!'
            })
          } else {
            this.leftLoading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '删除数据失败,请稍后再试!'
            })
          }
        })
    },
    leftHandleDelete () {
      if (this.leftSelectionList.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.leftLoading = true
          const idParams = { ids: this.leftIds }
          return this.$store.dispatch(removeSysDictTypesAction, idParams)
        })
        .then((res) => {
          this.leftLoading = false
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.$message({
              type: 'success',
              message: '批量删除操作成功!'
            })
            this.leftOnLoad(this.leftPage)
            this.$refs.left.toggleSelection()
          } else {
            this.leftLoading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '批量删除数据失败,请稍后再试!'
            })
          }
        })
    },
    leftRowClick (row, event, column) {
      const dictTypeId = row.id
      this.rightQuery = {
        dictTypeId
      }
      this.rightOnLoad(this.rightPage, this.rightQuery)
    },
    leftRefresh ({ page, searchForm }) {
      this.leftOnLoad(page)
      this.rightQuery = {}
      this.rightOnLoad(this.rightPage)
    },
    leftBeforeOpen (done, type) {
      if (['edit', 'view'].includes(type)) {
        const idParams = { id: this.leftForm.id }
        this.$store.dispatch(getSysDictTypeByIdAction, idParams).then((res) => {
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.leftForm = res.data
          } else {
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '查询数据失败,请稍后再试!'
            })
          }
        }).catch((err) => {
          console.log(err)
          this.$message({
            type: 'error',
            showClose: true,
            message: '查询数据异常,请稍后再试!'
          })
        })
      }
      done()
    },
    leftSearchReset () {
      this.leftQuery = {}
      this.rightQuery = {}
      this.leftOnLoad(this.leftPage)
      this.rightOnLoad(this.rightPage)
    },
    leftSearchChange (params, done) {
      done()
      this.leftQuery = params
      this.leftPage.currentPage = 1
      this.rightQuery = {}
      this.leftOnLoad(this.leftPage, params)
      this.rightOnLoad(this.rightPage)
    },
    leftSelectionChange (list) {
      this.leftSelectionList = list
    },
    leftSelectionClear () {
      this.leftSelectionList = []
      this.$refs.left.toggleSelection()
    },
    leftCurrentChange (currentPage) {
      this.leftPage.currentPage = currentPage
    },
    leftSizeChange (pageSize) {
      this.leftPage.pageSize = pageSize
    },
    leftOnLoad (page, params = {}) {
      this.leftLoading = true
      let queryData = {
        pageNo: page.currentPage,
        pageSize: page.pageSize
      }
      queryData = Object.assign(queryData, Object.assign(params, this.leftQuery))
      this.$store.dispatch(getSysDictTypePageListAction, queryData).then((res) => {
        this.leftLoading = false
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          const data = res.data
          this.leftPage.total = parseInt(data.total)
          this.leftData = data.records
          this.leftSelectionClear()
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '查询数据失败,请稍后再试!'
          })
        }
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'error',
          showClose: true,
          message: '查询数据异常,请稍后再试!'
        })
      })
    },
    // 右侧表格
    rightRowStyle ({ row, column, rowIndex }) {
      return {}
    },
    rightCellStyle ({ row, column, rowIndex, columnIndex }) {
      // return {
      //   color: 'green',
      //   fontWeight: 'bold',
      //   fontSize: '20'
      // }
      return {}
    },
    rightRowSave (row, loading, done) {
      loading()
      this.$store.dispatch(addSysDictDataAction, row).then((res) => {
        done()
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.rightOnLoad(this.rightPage)
          this.$message({
            type: 'success',
            message: '保存操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '保存数据失败,请稍后再试!'
          })
        }
      }, (error) => {
        done()
        console.log(error)
      })
    },
    rightRowUpdate (row, index, loading, done) {
      loading()
      this.$store.dispatch(updateSysDictDataAction, row).then((res) => {
        done()
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          this.rightOnLoad(this.rightPage)
          this.$message({
            type: 'success',
            message: '编辑操作成功!'
          })
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '编辑数据失败,请稍后再试!'
          })
        }
      }, (error) => {
        done()
        console.log(error)
      })
    },
    rightRowDel (row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.rightLoading = true
          const idParams = { id: row.id }
          return this.$store.dispatch(removeSysDictDataAction, idParams)
        })
        .then((res) => {
          this.rightLoading = false
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.rightOnLoad(this.rightPage)
            this.$message({
              type: 'success',
              message: '删除操作成功!'
            })
          } else {
            this.rightLoading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '删除数据失败,请稍后再试!'
            })
          }
        })
    },
    rightHandleDelete () {
      if (this.rightSelectionList.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.rightLoading = true
          const idParams = { ids: this.rightIds }
          return this.$store.dispatch(removeSysDictDatasAction, idParams)
        })
        .then((res) => {
          this.rightLoading = false
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.$message({
              type: 'success',
              message: '批量删除操作成功!'
            })
            this.rightOnLoad(this.rightPage)
            this.$refs.right.toggleSelection()
          } else {
            this.rightLoading = false
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '批量删除数据失败,请稍后再试!'
            })
          }
        })
    },
    rightRowClick (row, event, column) {
      this.$refs.right.rowView(row, column)
    },
    rightRefresh ({ page, searchForm }) {
      this.rightOnLoad(page)
    },
    rightBeforeOpen (done, type) {
      if (['edit', 'view'].includes(type)) {
        const idParams = { id: this.rightForm.id }
        this.$store.dispatch(getSysDictDataByIdAction, idParams).then((res) => {
          const resCode = res.code
          const errorMsg = res.message
          if (resCode === 0) {
            this.rightForm = res.data
          } else {
            this.$message({
              type: 'error',
              showClose: true,
              message: errorMsg || '查询数据失败,请稍后再试!'
            })
          }
        }).catch((err) => {
          console.log(err)
          this.$message({
            type: 'error',
            showClose: true,
            message: '查询数据异常,请稍后再试!'
          })
        })
      }
      done()
    },
    rightSearchReset () {
      this.rightQuery = {}
      this.rightOnLoad(this.rightPage)
    },
    rightSearchChange (params, done) {
      done()
      this.rightQuery = params
      this.rightPage.currentPage = 1
      this.rightOnLoad(this.rightPage, params)
    },
    rightSelectionChange (list) {
      this.rightSelectionList = list
    },
    rightSelectionClear () {
      this.rightSelectionList = []
      this.$refs.right.toggleSelection()
    },
    rightCurrentChange (currentPage) {
      this.rightPage.currentPage = currentPage
    },
    rightSizeChange (pageSize) {
      this.rightPage.pageSize = pageSize
    },
    rightOnLoad (page, params = {}) {
      this.rightLoading = true
      let queryData = {
        pageNo: page.currentPage,
        pageSize: page.pageSize
      }
      queryData = Object.assign(queryData, Object.assign(params, this.rightQuery))
      this.$store.dispatch(getSysDictDataPageListAction, queryData).then((res) => {
        this.rightLoading = false
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          const data = res.data
          this.rightPage.total = parseInt(data.total)
          this.rightData = data.records
          this.rightSelectionClear()
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '查询数据失败,请稍后再试!'
          })
        }
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'error',
          showClose: true,
          message: '查询数据异常,请稍后再试!'
        })
      })
    }
  },
  head () {
    return {
      title: '字典管理 | ' + this.website.name,
      meta: [
        { hid: 'description', name: 'description', content: '字典管理' }
      ]
    }
  }
}
</script>

<style scoped>
  .avue-view {
    padding: 0 10px!important;
    width: 100%;
    box-sizing: border-box;
  }
</style>
